package com.itheima.mongo.api;

import cn.hutool.core.collection.CollUtil;
import com.itheima.dubbo.api.UserLikeApi;
import com.itheima.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean love(Long userId, Long likeUserId, boolean like) {
        try {
            //构造查询数据
            Criteria criteria = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
            UserLike userLike = mongoTemplate.findOne(Query.query(criteria), UserLike.class);
            //判断是否存在
            if (userLike == null) {
                //不存在,保存
                userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setIsLike(like);
                mongoTemplate.save(userLike);
            } else {
                //存在就更新
                Update update = Update.update("like", like).set("updated", System.currentTimeMillis());
                mongoTemplate.updateFirst(Query.query(criteria), update, UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<Long> findlove(Long userId, Boolean islike) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("isLike").is(islike));
        List<UserLike> list = mongoTemplate.find(query, UserLike.class);
        //获取用户喜欢的用户id
        List<Long> ids = CollUtil.getFieldValues(list, "likeUserId", Long.class);
        return ids;
    }

    @Override
    public Integer findFan(Long userId, Boolean islike) {
        //创建查询条件
        Query query = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(islike));
        List<UserLike> list = mongoTemplate.find(query, UserLike.class);
        return list.size();
    }

    @Override
    public UserLike hxlike(Long likeUserId, Long userId) {
        //创建查询条件
        Query query = Query.query(Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId));
        UserLike like = mongoTemplate.findOne(query, UserLike.class);
        return like;
    }
}
